import calendar
import datetime
import random

from flask import Blueprint, current_app, make_response
from flask_cors import cross_origin
from flask import request

from app.Services.ProgramServices.ProgramServices import ProgramService
from app.Utils.Decorator.UserIdDecorator import inject_user_id
from app.Utils.Utils import success_response, error_response, return_response_

# 1. 创建蓝图对象
program_bp = Blueprint(
    name='program_bp',
    import_name=__name__,
    url_prefix='/work/project'
)
pro_services = ProgramService()

# 创建新的项目
@program_bp.route('/create', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def create_program(user_id):
    """
    创建项目接口.
    """
    program_info = {
        "user_id" : int(user_id),
        'program_name': request.json.get('project_name', None),
        'goal_id': request.json.get('goal_id', None),
        'program_desc': request.json.get('program_desc', None),
        'program_status': request.json.get('program_status', None),
        'create_time': datetime.datetime.now(),
        'update_time': datetime.datetime.now(),
        'attachment': request.json.get('attachment', None)
    }
     # 调用服务层创建项目
    status, msg, data = pro_services.create_program(
        user_id=program_info['user_id'],
        program_name=program_info['program_name'],
        goal_id=program_info['goal_id'],
        program_desc=program_info['program_desc'],  
        program_status=program_info['program_status'],
        attachment=program_info['attachment']
    )
    return return_response_(status, res=data.id,message=msg)

# 获取所有的项目（分页）
@program_bp.route('/get_all', methods=['GET'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def get_all_programs(user_id):
    """
    获取所有项目接口（分页）.
    """
    page = 1
    per_page = 50
    print("user_id:",user_id)
    status,msg, data = pro_services.get_programs_by_user(
        user_id=user_id,
        page=page,
        per_page=per_page
    )
    print(msg,data)
    return return_response_(status, res=data)


# 通过id更改项目信息
@program_bp.route('/update', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def update_program(user_id):
    """
    通过ID更改项目信息接口.
    """
    update_info = request.json
    update_info['user_id'] = user_id
    program_id = request.json.get('id', None)
    status,msg,data = pro_services.update_program(program_id=program_id,**update_info)
    return return_response_(status,res=msg,message=msg)

# 通过id删除项目
@program_bp.route('/delete', methods=['POST'])
@inject_user_id(default_user_id=1)  # 启用装饰器，默认值设为 1
def delete_program(user_id):
    """
    通过ID删除项目接口.
    """
    program_id = request.json.get('project_id', None)
    status, msg, data = pro_services.delete_program(
        program_id=program_id
    )
    return return_response_(status, res=data,message=msg)
